package org.wevil.config;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.wevil.anno.CustomIntrospector;
import org.wevil.anno.DictSerializerModifier;
import org.wevil.props.ResProp;

import javax.annotation.Resource;
import java.util.List;

/**
 * spring mvc 配置
 *
 * @author wanglei
 * @since 2020/2/1
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    private ResProp resProp;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 附件映射资源路径
        registry.addResourceHandler(resProp.getMappingPath() + "**")
                .addResourceLocations("file:" + resProp.getRootPath() + "/");
    }

    /**
     * 配置自定义序列化
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();

        // 数据脱敏 数字格式化 注解配置
        AnnotationIntrospector sis = objectMapper.getSerializationConfig().getAnnotationIntrospector();
        AnnotationIntrospector is1 = AnnotationIntrospectorPair.pair(sis, new CustomIntrospector());
        objectMapper.setAnnotationIntrospector(is1);
        converter.setObjectMapper(objectMapper);

        // 数据字典 注解配置
        SimpleModule module = new SimpleModule();
        module.setSerializerModifier(new DictSerializerModifier()); // 自定义的序列化修改器
        objectMapper.registerModule(module);
        MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter();
        converter2.setObjectMapper(objectMapper);

        converters.add(0, converter);
        converters.add(1, converter2);
    }
}